package com.admin.zhou.interceptor;

import com.admin.zhou.common.Const;
import com.admin.zhou.common.Tool;
import com.admin.zhou.redis.RedisUtil;
import com.admin.zhou.utils.RSAUtils;
import com.alibaba.druid.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class AdminIntercepter implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(AdminIntercepter.class);

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        String token = request.getHeader(Const.Admin_Token);


        if (StringUtils.isEmpty(token)){
            Tool.responeTo(response,"请先登录");
            return false;
        }

        String res = null;
        try {
            res = RSAUtils.decryptByPriKey(token, RSAUtils.PRIVATE_KEY);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (StringUtils.isEmpty(res)){
            Tool.responeTo(response,"请先登录");
            return false;
        }

        String[] result = res.split("-");

        String redisRes = (String) redisUtil.get(Const.REDIS_ADMIN+result[0]);

        if (redisRes != null && redisRes.equals(token)){
            request.setAttribute(Const.CURRENT_USER,result[0]);
            return true;
        }else{
            Tool.responeTo(response,"token失效");
            return false;
        }
    }

}
